package com.exception;

import com.Result;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    Logger log = LoggerFactory.getLogger(this.getClass());


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {

         //全局的BlockException异常处理  自动捕获
        log.info("异常:" + e.getRule());//getRule() 资源信息
        Result<Object> r = null;
        if (e instanceof FlowException) {
            r = new Result("限流了！！", 100);
        } else if (e instanceof DegradeException) {
            r = new Result("服務降級了！！", 101);
        } else if (e instanceof ParamFlowException) {
            r = new Result("熱點參數限流了！！", 102);
        } else if (e instanceof SystemBlockException) {
            r = new Result("觸發系統保護規則了", 103);
        } else {
            r = new Result("發生未知錯誤", 500);

        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), r);
    }

}
